package com.example.supermarketwrok.controller;

import com.example.supermarketwrok.model.Supermarket;
import com.example.supermarketwrok.service.SupermarketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class SupermarketController {
    @Autowired
    private SupermarketService supermarketService;

    @GetMapping("/")
    public String viewHomePage(Model model) { return findPaginated(1, "goodsName", "asc", model); }

    @GetMapping("/showSupermarketForm")
    public String showSupermarketForm(Model model) {
        Supermarket supermarket = new Supermarket();
        model.addAttribute("supermarket", supermarket);
        return "new_super";
    }

    @PostMapping("/saveSupermarket")
    public String saveSupermarket(@ModelAttribute("goods") Supermarket supermarket) {
        supermarketService.saveSupermarket(supermarket);
        return "redirect:/";
    }

    @GetMapping("/showFormForUpdate/{id}")
    public String showFormForUpdate(@PathVariable(value = "id") long id, Model model) {
        Supermarket goods = supermarketService.getSupermarketById(id);
        model.addAttribute("supermarket", goods);
        return "update_super";
    }

    @GetMapping("/deleteSupermarket/{id}")
    public String deleteSupermarket(@PathVariable(value = "id") long id) {
        this.supermarketService.deleteSupermarketById(id);
        return "redirect:/";
    }

    @GetMapping("/query{newGoodsName}")
    public String query(@PathVariable(value = "newGoodsName") String newGoodsName, Model model) {
        List<Supermarket> listGoodsNumber = supermarketService.findByGoodsName(newGoodsName);
        model.addAttribute("listSupermarket", listGoodsNumber);
        return "index";
    }


    //获取分页数据
    @GetMapping("/page/{pageNo}")
    public String findPaginated(@PathVariable(value = "pageNo") int pageNo,
                                @RequestParam("sortField") String sortField,
                                @RequestParam("sortDir") String sortDir,
                                Model model) {
        int pageSize = 5;

        Page<Supermarket> page = supermarketService.findPaginated(pageNo, pageSize, sortField, sortDir);
        List<Supermarket> listSupermarket = page.getContent();

        model.addAttribute("currentPage", pageNo);
        model.addAttribute("totalPages", page.getTotalPages());
        model.addAttribute("totalItems", page.getTotalElements());

        model.addAttribute("sortField", sortField);
        model.addAttribute("sortDir", sortDir);
        model.addAttribute("reverseSortDir", sortDir.equals("asc") ? "desc" : "asc");

        model.addAttribute("listSupermarket", listSupermarket);
        return "index";
    }
}
